package com.weavernorth.action.jb.utils;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.xpath.operations.Bool;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import sun.misc.BASE64Encoder;
import weaver.general.BaseBean;
import weaver.general.Util;

import java.io.IOException;
import java.util.Iterator;

/**
 * @Author: bruseewang
 * @Package: com.weavernorth.action.jb.utils
 * @date: 2020/5/15 9:42
 * @description:
 */
public class sendDataToSapUtils {
    /***
     * 构建xml的请求体
     * @param strYgbh:员工编号
     * @param strDate:开始日期
     * @param strFgsMb:工资项：法定节假日||非法定节假日
     * @param strFfjbzss:数值
     */
    public static String buildRequestXml(String strYgbh,String strDate,String strFgsMb,String strFfjbzss){
        //推送SAP 的xml拼接
        StringBuffer strRequestXml = new StringBuffer();
        strRequestXml.append("<soapenv:Envelope xmlns:soapenv='http://schemas.xmlsoap.org/soap/envelope/' xmlns:urn='urn:sap-com:document:sap:rfc:functions'>");
        strRequestXml.append("<soapenv:Header/>");
        strRequestXml.append("<soapenv:Body>");
        strRequestXml.append("<urn:ZHRI_084>");
        strRequestXml.append("<T_P2010>");
        strRequestXml.append("<item>");
        strRequestXml.append("<PERNR>"+strYgbh+"</PERNR>");//员工编号
        strRequestXml.append("<BEGDA>"+strDate+"</BEGDA>");//开始日期
        strRequestXml.append("<LGART>"+strFgsMb+"</LGART>");//工资项
        strRequestXml.append("<ANZHL>"+strFfjbzss+"</ANZHL>");//数值
        strRequestXml.append("</item>");
        strRequestXml.append("</T_P2010>");
        strRequestXml.append("<T_RETURN>");
        strRequestXml.append("<item>");
        strRequestXml.append("<TYPE></TYPE>");
        strRequestXml.append("<ID></ID>");
        strRequestXml.append("<NUMBER></NUMBER>");
        strRequestXml.append("<MESSAGE></MESSAGE>");
        strRequestXml.append("<LOG_NO></LOG_NO>");
        strRequestXml.append("<LOG_MSG_NO></LOG_MSG_NO>");
        strRequestXml.append("<MESSAGE_V1></MESSAGE_V1>");
        strRequestXml.append("<MESSAGE_V2></MESSAGE_V2>");
        strRequestXml.append("<MESSAGE_V3></MESSAGE_V3>");
        strRequestXml.append("<MESSAGE_V4></MESSAGE_V4>");
        strRequestXml.append("</item>");
        strRequestXml.append("</T_RETURN>");
        strRequestXml.append("</urn:ZHRI_084>");
        strRequestXml.append("</soapenv:Body>");
        strRequestXml.append("</soapenv:Envelope>");
        return strRequestXml.toString();
    }

    /***
     * 向接口发送请求
     * @param strUrl:请求接口地址
     * @param strRequestXml：请求包体
     * @param strEncoding：编码格式
     * @param strProperties：属性文件名(存放用户名密码,用于接口验证)
     * @return
     * @throws IOException
     */
    public static String sendPost(String strUrl, String strRequestXml, String strEncoding,String strProperties) throws IOException {
        //基础类
        BaseBean bb = new BaseBean();
        String strBody = null;
        //创建httpclient对象
        CloseableHttpClient client = HttpClients.createDefault();

        //创建post方式请求对象
        try {
            HttpPost httpPost = new HttpPost(strUrl);


            //装填参数
            StringEntity stringEntity = new StringEntity(strRequestXml, "utf-8");
            //log.info("请求xml=" + strRequestXml);
            //设置参数到请求对象中
            httpPost.setEntity(stringEntity);
            //log.info("请求地址=" + strUrl);
            //获取用户名
            String strUsername = Util.null2String(bb.getPropValue(strProperties, "username"));
            bb.writeLog("获取用户名=" + strUsername);
            //获取密码
            String strPassword = Util.null2String(bb.getPropValue(strProperties, "password"));
            bb.writeLog("获取密码=" + strPassword);
            //sap的接口需验证
            String strValue = "Basic " + (new BASE64Encoder().encode((strUsername + ":" + strPassword).getBytes()));
            bb.writeLog("sap的接口需验证=" + strValue);
            httpPost.setHeader("Authorization", strValue);
            httpPost.setHeader("Content-Type", "text/xml;charset=UTF-8");

            //执行请求操作，并拿到结果（同步阻塞）
            CloseableHttpResponse response = client.execute(httpPost);
            //获取结果实体
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                //按指定编码转换结果实体为String类型
                strBody = EntityUtils.toString(entity, strEncoding);
                bb.writeLog("返回结果=" + strBody);
            }
            //关闭底层流
            EntityUtils.consume(entity);
            //释放链接
            response.close();
        } catch (Exception e) {
            bb.writeLog("发送请求异常捕获:"+e.toString());
        }finally {
            return strBody;
        }

    }

    public static String[] responseResult(String responseXml){
        String[] strResult=new String[2];
        try {
            Document doc=null;//引用dom4j组件
            doc = DocumentHelper.parseText(responseXml.toString());
            //selectNodes("Type")从当前节点的子节点中选择名为“Type”的节点
            //selectNodes("/Type")从根节点的子节点中选择名为“Type”的节点
            //selectNodes("//Type")从任意节点上选择名为“Type”的节点
            Iterator<Element> its2 = doc.selectNodes("//TYPE").iterator();
            int intType = 0;
            String resultCode=null;//接口返回状态码
            Boolean bolFlag=true;
            String strMessage="";
            while (its2.hasNext()){
                Element element = its2.next();
                resultCode=element.getText();
                if ("E".equals(resultCode)) {
                    bolFlag = false;
                    break;
                }
                intType++;
            }
            int intMess = 0;
            //返回值失败时,则提示失败
            if ("E".equals(resultCode)) {
                Iterator<Element> its3 = doc.selectNodes("//MESSAGE").iterator();
                while (its3.hasNext()) {
                    Element element2 = its3.next();
                    strMessage = element2.getText();
                    if (intMess == intType) {
                        if (!"".equals(strMessage)) {
                            bolFlag = false;
                            break;
                        }
                    }
                    intMess++;
                }
            }
            if (!bolFlag) {
                strResult[0]="f";
                strResult[1]=strMessage;
            } else {
                strResult[0]="s";
                strResult[1]="SUCCESS";
            }
        }catch (Exception e) {
            strResult[0]="e";
            strResult[1]=e.toString();
        }finally {
            return strResult;
        }
    }


    //查询节点是否存在
    public static Boolean eleisExists(String strXml,String strElement) {
        try {
            Document doc=null;//引用dom4j组件
            doc = DocumentHelper.parseText(strXml.toString());
            Integer count=0;
                    count= doc.selectNodes(strElement).size();
            if(count>0){
                return true;
            }
            else{
                return false;
            }
        }catch (Exception e){
            return false;
        }

    }
}
